/**
 * Created by BaiYJ on 2017/4/21.
 */

// $(document).ready(function() {
//     $('#houseTable').DataTable();
// } );
var editor; // use a global for the submit and return data rendering
var table;
var userTypeId = 0;
var user;
var communityId = "";
function getUrl(url, params) {
    for (var i = 0; i < params.length; i++) {
        if ($("#" + params[i]).val() != "") {
            url = url + "&" + params[i] + "=" + $("#" + params[i]).val();
        }
    }
    return url;

}

function jsGetAge(strBirthday){
    var returnAge;
    var strBirthdayArr=strBirthday.split("-");
    var birthYear = strBirthdayArr[0];
    var birthMonth = strBirthdayArr[1];
    var birthDay = strBirthdayArr[2];

    d = new Date();
    var nowYear = d.getFullYear();
    var nowMonth = d.getMonth() + 3;
    if(nowMonth>12){
        nowMonth=nowMonth-12;
        nowYear=nowYear+1
    }
    var nowDay = d.getDate();

    if(nowYear == birthYear){
        returnAge = 0;//同年 则为0岁
    }
    else{
        var ageDiff = nowYear - birthYear ; //年之差
        if(ageDiff > 0){
            if(nowMonth == birthMonth) {
                var dayDiff = nowDay - birthDay;//日之差
                if(dayDiff < 0)
                {
                    returnAge = ageDiff - 1;
                }
                else
                {
                    returnAge = ageDiff ;
                }
            }
            else
            {
                var monthDiff = nowMonth - birthMonth;//月之差
                if(monthDiff < 0)
                {
                    returnAge = ageDiff - 1;
                }
                else
                {
                    returnAge = ageDiff ;
                }
            }
        }
        else
        {
            returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
        }
    }

    return returnAge;//返回周岁年龄

}

$(document).ready(function () {
    $.ajax({
        url: '/commis/api/user/currentUser',
        type: "GET",
        async: false,
        dataType: 'json',
        data: {},
        success: function (response) {
            if (response.status == 0) {
                console.log("用户存在");
                var user = response.data;
                userTypeId = user.userTypeId;
                if (userTypeId == 4) {
                    communityId = user.communityId;
                }
                console.log(userTypeId);
            } else if (response.status == 1) {
                alert("登录用户已经过期，请重新登录");
                window.parent.location.href = "../../login.html";
            }
        }, error: function (msg) {
            alert("登录用户已经过期，请重新登录");
            window.parent.location.href = "../../login.html";
        }
    })
    $.ajax({
        url: '/commis/api/community/all',
        async: false,
        dataType: 'json',
        success: function (response) {
            for (var i = 0; i < response.length; i++) {
                $("#community").append("<option value='" + response[i].communityId + "'>" + response[i].communityName + "</option>");
            }

        }, error: function () {
            alert("发生错误");
            window.parent.location.href = "../../login.html";
        }
    });
    $.ajax({
        url: '/commis/api/positionType/all',
        async: false,
        dataType: 'json',
        success: function (response) {
            console.log(response.length);
            for (var i = 0; i < response.length; i++) {

                $("#positionId").append("" +
                    "<option value='" + response[i].positionId + "'>" + response[i].positionName + "</option>");
            }


        }, error: function () {

        }
    });
    $('#sWorkDate').datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true,
        todayBtn: true,


    });
    $('#leavedate').datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true,
        todayBtn: true,


    });
    $('#registerTime').datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true,
        todayBtn: true


    });
    $("#inputfile").fileinput({
        uploadUrl: "/commis/api/person/import", // server upload action
        uploadAsync: true,
        showPreview: false,
        language: 'zh',
        maxFileCount: 1,
        elErrorContainer: ".file-error",
        allowedFileExtensions: ["xls", "xlsx"]
    }).on("fileuploaded", function (event, data, id, index) {
        var response = data.response;
        var status = response.status;
        var out;
        if (status == 0) {
            out = '上传数据成功.';
            alert("上传数据成功");
        }

        else if (status == 1) {
            alert("上传数据失败");
        } else {
            out = response.msg;
            alert(response.msg);

        }
        $('.file-success').html(out);
        $('.file-success').fadeIn('slow');


    }).on('fileclear', function (event) {
        $('#inputfile').val("");
        $('.file-success').hide();

    });


    editor = new $.fn.dataTable.Editor({
        ajax: {
            create: {
                type: 'POST',
                url: '/commis/api/person/create'
            },
            edit: {
                type: 'PUT',
                url: '/commis/api/person/edit?id=_id_'
            },
            remove: {
                type: 'DELETE',
                url: '/commis/api/person/remove?id=_id_'
            }
        },
        i18n: {
            create: {
                title: "新增记录",
                submit: "添加"
            },
            edit: {
                title: "修改记录",
                submit: "修改",
                confirm: "您确定要修改这 %d 条记录吗?"
            },
            remove: {
                title: "删除记录",
                submit: "删除",
                confirm: "您确定要删除这 %d 条记录吗?"
            }
        },
        idSrc: 'personId',
        table: "#personTable",
        fields: [{
            label: "所属社区:",
            name: "communityId",
            type: "select"
        }, /*{
         label: "所属部门:",
         name: "departId",
         type: "select"
         }, */{
            label: "人员姓名:",
            name: "personName"
        },{
            label: "序号:",
            name: "number"
        }, {
            label: "职位类别:",
            name: "positionId",
            type: "select"
        }, {
            label: "性别:",
            name: "sex",
            type: "select",
            options: ["男", "女"]
        }, {
            label: "出生年月:",
            name: "birthday",
            type: 'datetime',
            def: function () {
                return new Date();
            }
        }, {
            label: "学历:",
            name: "education",
            type: "select",
            options: ["博士", "硕士", "本科", "大专", "中专", "高中", "初中", "小学", "无"]
        }, {
            label: "政治面貌:",
            name: "personPolitica"
        }, {
            label: "民族:",
            name: "nationality"
        }, {
            label: "到岗日期:",
            name: "sWorkDate",
            type: 'datetime',
            def: function () {
                return new Date();
            }
        }, {
            label: "户籍地址:",
            name: "householdAddr"
        }, {
            label: "居住地址:",
            name: "liveAddr"
        }, {
            label: "家庭电话:",
            name: "familyPhone"
        }, {
            label: "手机号码:",
            name: "mobilePhone"
        }, {
            label: "身份证号:",
            name: "cardCode"
        }, {
            label: "资格证书编号:",
            name: "icetuCode"
        }, {
            label: "证书级别:",
            name: "ccId",
            type: "select"
        }, {
            label: "证书日期:",
            name: "ccDate",
            type: 'datetime',
            def: function () {
                return new Date();
            }
        }, {
            label: "应招类型:",
            name: "enlistType",
            type: "select",
            options: ["社招", "返聘"]
        }, {
            label: "是否实习期:",
            name: "isIntern",
            type: "radio",
            options: [
                {
                    label: "是",
                    value: "1"
                }, {
                    label: "否",
                    value: "0"
                }
            ]
        }, {
            label: "是否独生子女:",
            name: "isDszn",
            type: "radio",
            options: [
                {
                    label: "是",
                    value: "1"
                }, {
                    label: "否",
                    value: "0"
                }
            ]
        }, {
            label: "独生子女费截止日期:",
            name: "dsznDeadline",
            type: 'datetime',
            def: function () {
                return new Date();
            }
        }, {
            label: "是否住在本社区:",
            name: "liveCommunity",
            type: "radio",
            options: [
                {
                    label: "是",
                    value: "1"
                }, {
                    label: "否",
                    value: "0"
                }
            ]
        }, {
            label: "是否住在本街道:",
            name: "liveAvenue",
            type: "radio",
            options: [
                {
                    label: "是",
                    value: "1"
                }, {
                    label: "否",
                    value: "0"
                }
            ]
        }, {
            label: "职务年限补贴:",
            name: "zwnxbt"
        }, {
            label: "养老:",
            name: "pension"
        }, {
            label: "医疗:",
            name: "medicare"
        }, {
            label: "失业:",
            name: "unemployment"
        }, {
            label: "公积金:",
            name: "providentFund"
        }, {
            label: "个人所得税:",
            name: "incomeTax"
        }, {
            label: "补发:",
            name: "backPay"
        }, {
            label: "补扣公积金:",
            name: "supPf"
        }, {
            label: "补扣三险:",
            name: "supI"
        }
        ]
    });

    var buttons = [];
    var select = true;
    if (userTypeId == 1) {
        $(".communityDiv").show();
        select = true;
        buttons = [
            {extend: "create", editor: editor, text: "添加", className: 'btn btn-primary'},
            {extend: "edit", editor: editor, text: "修改", className: 'btn btn-primary'},
            {extend: "remove", editor: editor, text: "删除", className: 'btn btn-danger'}
        ];
        console.log(buttons);


    } else if (userTypeId == 2) {
        $(".communityDiv").show();
        $("#sqjsSpan").show();
        $("#sqjsDiv").show();

        select = true;
        buttons = [
            {extend: "edit", editor: editor, text: "修改", className: 'btn btn-primary'},
            {extend: "remove", editor: editor, text: "删除", className: 'btn btn-danger'}
        ];

    } else if (userTypeId == 3||userTypeId == 6||userTypeId == 7||userTypeId == 8||userTypeId == 9) {
        $(".communityDiv").show();
        select = false;
        buttons = [];

    } else if (userTypeId == 4) {
        $(".communityDiv").hide();
        select = false;
        buttons = [];
    }else if (userTypeId ==5) {
        $(".communityDiv").hide();
        select = false;
        buttons = [];

    }
    table = $('#personTable').DataTable({

        dom: "Bfrtip",
        ajax: "/commis/api/person/pageDatatables?communityId=" + communityId+"&userTypeId="+ userTypeId,
        autoWidth: true,
        responsive: true,
        serverSide: true,
        processing: true,
        lengthChange: false,//是否允许用户改变表格每页显示的记录数
        ordering: false,//是否允许用户排序
        paging: true,//是否分页
        pagingType: "full_numbers",//除首页、上一页、下一页、末页四个按钮还有页数按钮
        searching: false,//是否开始本地搜索
        stateSave: false,//刷新时是否保存状态
        autoWidth: true,//自动计算宽度
        createdRow: function ( row, data, index ) {
            var curr= new  Date();
            var birth =data["birthday"];
            if ( jsGetAge(birth)>=55) {//距55岁剩两月内的显示红色
                // $('td', row).css("color","red");
                // $('td', row).css('backgroundColor','#FF0000')
                // $('td', row).eq(3).css('font-weight',"bold").css("color","red");
                $('td', row).css('backgroundColor', '#f8c4c4');
                // $('tr', row).css("color","red");
            }
        },

        language: {
            emptyTable: "没有数据",
            search: "搜索:",
            paginate: {
                first: "首页",
                previous: "上一页",
                next: "下一页",
                last: "尾页"

            },
            select: {
                rows: {
                    _: "选中 %d 行",
                    1: "选中 1 行"
                }/*,
                 columns: "选中 %d 列"*/
            },
            lengthMenu: "每页 _MENU_ 条记录",
            zeroRecords: "没有找到记录",
            info: "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )，共 _TOTAL_ 项",
            infoEmpty: "无记录",
            infoFiltered: "(从 _MAX_ 条记录过滤)"
        },
        columns: [
            {
                data: 'number', defaultContent: ""
            },
            {
                data: 'community.communityName', defaultContent: ""
            }, /*{
             data: 'depart.departName', defaultContent: ""
             },{
                data: 'user.realName', defaultContent: ""
            },*/  {
                data: 'personName', defaultContent: ""
            }, {
                data: 'positionType.positionName', defaultContent: ""
            }, {
                data: 'sex', defaultContent: ""

            }, {
                data: 'birthday', defaultContent: ""

            }, {
                data: 'education', defaultContent: ""

            }, {
                data: 'personPolitica', defaultContent: ""

            }, {
                data: 'nationality', defaultContent: ""
            }, {
                data: 'sWorkDate', defaultContent: ""
            }, {
                data: 'leaveStatus',
                render: function (data, type, row) {
                    // Combine the first and last names into a single table field
                    if (1 == data) {
                        return "已离职";
                    } else {
                        return "未离职"
                    }
                }
            }, {
                data: 'leavedate', defaultContent: ""
            }, {
                data: 'householdAddr', defaultContent: ""
            }, {
                data: 'liveAddr', defaultContent: ""
            }, {
                data: 'familyPhone', defaultContent: ""
            }, {
                data: 'mobilePhone', defaultContent: ""
            }, {
                data: 'cardCode', defaultContent: ""
            }, {
                data: 'icetuCode', defaultContent: ""
            }, {
                data: 'personCc.ccName', defaultContent: ""
            }, {
                data: 'ccDate', defaultContent: ""
            }, {
                data: 'enlistType', defaultContent: ""
            }, {
                data: 'isIntern',
                render: function (data, type, row) {
                    // Combine the first and last names into a single table field
                    if (1 == data) {
                        return "是";
                    } else {
                        return "否"
                    }
                }
            }, {
                data: 'isDszn',
                render: function (data, type, row) {
                    // Combine the first and last names into a single table field
                    if (1 == data) {
                        return "是";
                    } else {
                        return "否"
                    }
                }
            }, {
                data: 'dsznDeadline', defaultContent: ""
            }, {
                data: 'liveCommunity',
                render: function (data, type, row) {
                    // Combine the first and last names into a single table field
                    if (1 == data) {
                        return "是";
                    } else {
                        return "否"
                    }
                }
            }, {
                data: 'liveAvenue',
                render: function (data, type, row) {
                    // Combine the first and last names into a single table field
                    if (1 == data) {
                        return "是";
                    } else {
                        return "否"
                    }
                }
            }, {
                data: 'zwnxbt', defaultContent: ""
            }, {
                data: 'pension', defaultContent: ""
            }, {
                data: 'medicare', defaultContent: ""
            }, {
                data: 'unemployment', defaultContent: ""
            }, {
                data: 'providentFund', defaultContent: ""
            }, {
                data: 'incomeTax', defaultContent: ""
            }, {
                data: 'backPay', defaultContent: ""
            }, {
                data: 'supPf', defaultContent: ""
            }, {
                data: 'supI', defaultContent: ""
            }, {
                data: 'registerTime', defaultContent: ""
            }], select: select,
        buttons: buttons

    });


    if(userTypeId==4){
        table.column(10).visible(false);
        table.column(11).visible(false);
    }
    $('#search').on('click', function () {

        var url = "/commis/api/person/pageDatatables?1=1"
        if(userTypeId==4){
            url=url+"&userTypeId=" + 4;
        }

        if (userTypeId != 4) {
            communityId = $('#community').val();

        }
        url = url + "&communityId=" + communityId;

        var params = ["personName", "year", "month", "education", "sex", "age", "personPolitica", "positionId", "registerTime","leavedate", "sWorkDate", "orderName"];
        url = getUrl(url, params);


        table.ajax.url(url).load();
    });

    $('#addWage').on('click', function () {


        if(confirm("确定增加当年职务补贴吗?")){
            if(confirm("添加后将会为符合条件的人员增加50元职务补贴，请确认是否添加？")) {
                if(confirm("添加后，请务必今年不要再点击添加职务补贴进行添加，请确认是否知晓?")){
                    $.ajax({
                        url: '/commis/api/person/addwage',
                        async: false,
                        dataType: 'json',
                        success: function (response) {
                            if(response.status==0){
                                alert("增加职务年限补贴成功");
                                table.ajax.reload();
                            }else if(response.status==5){
                                if(confirm("只有一月份才能更新职务年限补贴,若想继续添加，请点击确定，后果自负！")){
                                    if(confirm("继续添加，后果自负，请确认是否知晓?")){
                                        $.ajax({
                                            url: '/commis/api/person/addwage?flag=1',
                                            async: false,
                                            dataType: 'json',
                                            success: function (response) {
                                                if(response.status==0){

                                                    table.ajax.reload();
                                                    alert("增加职务年限补贴成功");
                                                }else{
                                                    alert(response.msg);
                                                };



                                            }, error: function () {
                                                alert("发生错误");
                                            }
                                        });


                                    }

                                }
                            }else{
                                alert(response.msg);
                            };



                        }, error: function () {
                            alert("发生错误");
                        }
                    });
                }
            }



        }



    });




})
//设置框架
$(function () {
    $("#index_style").frame({
        float: 'left',
        menu_nav: '.Quick_operation',
        color_btn: '.skin_select',
        Sellerber_menu: '.list_content',
        Sellerber_header: '.Sellerber_header',
    });
});
$("#iframe_box").niceScroll({
    cursorcolor: "#888888",
    cursoropacitymax: 1,
    touchbehavior: false,
    cursorwidth: "5px",
    cursorborder: "0",
    cursorborderradius: "5px"
});
/*********************/
require.config({
    paths: {
        echarts: './js/dist'
    }
});